var app=getApp()
var moduleUrl=app.baseUrl+'/client/event'
import parse from 'mini-html-parser2';
import dayjs from 'dayjs';
Page({
  data: {
    loading: true, // 初始加载状态
    imageLoaded: false, // 新增加载进度
    progress: 0 // 新增加载进度
  },
  onLoad(e) {
    this.setData({ 
      baseUrl: app.baseUrl,
      eventId: e.id
    });
    
    // 开始加载
    this.setData({ loading: true });
    
    // 真实数据请求
    this.getEventByID(e.id)
      .then(() => {
        this.setData({ loading: false });
      })
      .catch(err => {
        console.error('加载失败:', err);
        this.setData({ loading: false });
      });
  },
  onShow() {
    this.getEventByID(this.data.eventId)
  },
  getEventByID(id) {
    const updateProgress = (value) => {
      this.setData({ progress: Math.min(value, 100) });
    };
    
    return new Promise((resolve, reject) => {
      var that = this
      //查出所有处于报名阶段的活动
      dd.httpRequest({
        url: moduleUrl+'/detail',
        method: 'GET',
        data:{
          eventId:id,
          userId:app.userId
        },
        success: function(res) {  
        console.log(moduleUrl+'/detail',res.data.data)
         that.setData({
           event:res.data.data
         })
         res.data.data.description=res.data.data.description.replace(/\<img/gi, '<img style="width:100%;height:auto"');
         parse(res.data.data.description, function(err, nodes) {
          if (!err) {
            var imgMap = {};
            var processedNodes = nodes.map(function(node) {
              if (node.children && node.children[0] && node.children[0].name === 'img') {
                var imgNode = node.children[0];
                var originalSrc = (imgNode.attrs && imgNode.attrs.src) || '';
                
                if (originalSrc) {
                  var fullSrc = originalSrc.startsWith('/prod-api') 
                    ? that.data.baseUrl.replace('/prod-api', '') + originalSrc  // 如果原始路径已包含则去掉baseUrl中的prod-api
                    : that.data.baseUrl + originalSrc;  // 否则正常拼接
                  
                  imgNode.attrs.src = fullSrc;
                  imgMap[originalSrc] = fullSrc;
                }
                
                if (imgNode.attrs) {
                  imgNode.attrs.style = imgNode.attrs.style || 'width:100%;height:auto;';
                }
              }
              return node;
            });

            var updateData = { nodes: processedNodes };
            Object.keys(imgMap).forEach(function(key) {
              updateData[key] = imgMap[key];
            });

            that.setData(updateData);
          } else {
            console.error('富文本解析失败:', err);
          }
        });
      
        console.log("res.data.data.description",res.data.data.description)
        console.log("node",that.data.nodes)
         console.log("1231",that.data.event)
         var now = new Date();
         var year = now.getFullYear(); // 获取年份
         var month = now.getMonth() + 1; // 获取月份，月份从0开始，所以需要+1
         var day = now.getDate(); // 获取日期
         var date2=year + "-" + month + "-" + day
         console.log(date2)
         console.log("要看"+that.data.event)
         console.log(that.data.event)
         var compare= that.compareDates(that.data.event.signupEnd,date2)
         that.setData({
           compare:compare
         })
        //  for(node in that.data.nodes){
          // if(node.children[0].name='img'){
          //   console.log('img')
          // }
          // console.log('1')
        //  }
         updateProgress(70);
         
         // 添加状态映射
         let eventData = res.data.data;
         eventData.eventStatus = that.getEventStatusText(eventData.eventStatus);
         
         that.setData({
           event: eventData
         })
         
         resolve(res);
        },
        fail: function(res) {
          // dd.alert({content: JSON.parse(res.originalData).rows'});
        },
        complete: function(res) {
          // dd.alert({content: 'complete'});
        }
      });
    });
  },

applyevent(eventId){
  var that =this
  //查出所有处于报名阶段的活动
    dd.httpRequest({
      url: app.baseUrl+'/client/event'+'apply',
      method: 'POST',
      data:JSON.stringify({
        eventID:eventId,
        userId:app.userId
      }),
      success: function(res) {  
      console.log(JSON.parse(res.originalData).rows[0])
       
      //  console.log("1231",that.data.event)
      },
      fail: function(res) {
        // dd.alert({content: JSON.parse(res.originalData).rows'});
      },
      complete: function(res) {
        // dd.alert({content: 'complete'});
      }
    });
},

compareDates(dateStr1, dateStr2) {
  // 将日期字符串转换为Date对象
  var date1 = new Date(dateStr1);
  var date2 = new Date(dateStr2);
  console.log(dateStr1)
  console.log(dateStr2)
  console.log(date2)
  console.log(date1)

  // 比较时间戳
  if (date1.getTime() < date2.getTime()) {
      return -1; // dateStr1 是更早的日期
  } else if (date1.getTime() > date2.getTime()) {
      return 1; // dateStr2 是更早的日期
  } else {
      return 0; // 两个日期相等
  }
},
openMap() {
  // 从后端获取的活动地点信息
  const location = this.data.event.position;
  const longitude = this.data.event.longitude || 120.18617500000005; // 如果后端有提供经纬度就用后端的
  const latitude = this.data.event.latitude || 30.19188000000001;
  
  // dd.openLocation({
  //   longitude: longitude,
  //   latitude: latitude,
  //   name: location,
  //   address: location,
  //   scale: 18
  // });
},

handleImageLoad() {
  this.setData({ imageLoaded: true });
},

processEventData(data) {
  // 统一处理日期格式
  const formatDate = (dateStr) => dayjs(dateStr).format('YYYY-MM-DD HH:mm');
  
  this.setData({
    event: {
      ...data,
      eventBegin: formatDate(data.eventBegin),
      eventEnd: formatDate(data.eventEnd),
      signupBegin: formatDate(data.signupBegin),
      signupEnd: formatDate(data.signupEnd)
    }
  });
},

// 添加状态映射方法
getEventStatusText(status) {
  const statusMap = {
    1: '未开始报名',
    2: '报名中',
    3: '等待活动开始',
    4: '活动进行中'
  };
  return statusMap[status] || '未知状态';
}

});
